package com.sanuo.pico.view;

import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.AppCompatImageView;

import com.sanuo.pico.R;
import com.sanuo.pico.it.TouchUpListener;


public class TouchUpImageView extends AppCompatImageView implements TouchUpListener {

    int upBg, downBg, upSrc, downSrc;

    private TouchUpListener listener;

    public TouchUpImageView(@NonNull Context context) {
        this(context, null);
    }

    public TouchUpImageView(@NonNull Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public TouchUpImageView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        TypedArray ta = getContext().obtainStyledAttributes(attrs, R.styleable.TouchColor);
        upBg = ta.getResourceId(R.styleable.TouchColor_up_bg, 0);
        downBg = ta.getResourceId(R.styleable.TouchColor_down_bg, 0);
        upSrc = ta.getResourceId(R.styleable.TouchColor_up_src, 0);
        downSrc = ta.getResourceId(R.styleable.TouchColor_down_src, 0);
        ta.recycle();
    }

    public TouchUpImageView setTouchUpListener(TouchUpListener l) {
        listener = l;
        return this;
    }

    @Override
    public void onTouchUp() {
        if (upSrc != 0) {
            setImageResource(upSrc);
        }
        if (upBg != 0) {
            setBackgroundResource(upBg);
        }
        if (listener != null) {
            listener.onTouchUp();
        }
    }

    @Override
    public boolean onTouchDown() {
        if (downBg != 0) {
            setBackgroundResource(downBg);
        }
        if (downSrc != 0) {
            setImageResource(downSrc);
        }
        if (listener != null) {
            return listener.onTouchDown();
        }
        return false;
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        listener = null;
    }
}
